<template>
  <div class="college-statistics">
    <!-- 筛选栏 -->
    <el-card class="filter-card">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-select
              v-model="currentCollege"
              placeholder="请选择学院"
              @change="handleCollegeChange"
              style="width: 100%"
          >
            <el-option
                v-for="item in colleges"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-col>
      </el-row>
    </el-card>

    <!-- 图表区域 -->
    <el-row :gutter="24" class="chart-row">
      <!-- 饼图 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>各专业人数分布</span>
              <el-tooltip content="点击切换数据显示" placement="top">
                <el-icon @click="togglePieLabel"><pie-chart /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>登录日志</span>
            </div>
          </template>
          <div  class="chart-container">
            <el-table
                :data="logData"
                height="43vh"
                border
                stripe
                highlight-current-row
            >
              <el-table-column prop="username" label="用户名"  align="center" />
              <el-table-column prop="date" label="时间" align="center" />
              <el-table-column prop="ip" label="IP地址"  align="center" />
              <el-table-column fixed="right" label="状态" width="107" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'in' ? 'success' : 'danger'">
                    {{ scope.row.status === 'in' ? '登录' : '登出' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
                @current-change="handlePageChange"
                :current-page="currentPage"
                :page-size="pageSize"
                layout="total, prev, pager, next, jumper"
                :total="dataLength">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import * as echarts from 'echarts';

import request from "@/requests/request.js";

const mockData = ref([])
// 模拟学院数据
const colleges = ref([])
const dataLength = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const logData = ref([])
// 响应式数据
const currentCollege = ref('1');
const pieChartRef = ref(null);
let pieChart = null;
const handleCollegeChange = (value) => {
  currentCollege.value = value;

}

// 初始化图表
onMounted(async () => {
  try {
    request.get('log/get-login-log', {
      params: {
        page: currentPage.value,
        size: 5
      }
    }).then(res => {
      dataLength.value = res.data.data['total']
      logData.value = res.data.data['logs']
    })
    // 获取学院数据
    const collegeRes = await request.get('/college/get-college-tree');
    colleges.value = collegeRes.data.data;
    if (colleges.value.length > 0) {
      currentCollege.value = colleges.value[0].id;
    }

    // 获取各学院各专业人数数据
    const dataRes = await request.get('/major/get-all-college-major-info');
    mockData.value = dataRes.data.data;

    // 初始化图表
    initPieChart();
    loadData(currentCollege.value);
  } catch (error) {
    console.error('请求失败:', error);
  }
});

// 销毁时清理
watch([() => pieChartRef.value], ([newPie], [oldPie]) => {
  if (oldPie) oldPie.dispose();
}, { deep: true, immediate: true });

// 饼图初始化
const initPieChart = () => {
  pieChart = echarts.init(pieChartRef.value);
  pieChart.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c}人 ({d}%)' },
    series: [{
      type: 'pie',
      radius: ['40%', '70%'],
      itemStyle: { borderRadius: 8 },
      label: { show: false, position: 'outside' },
      emphasis: { shadowBlur: 10 }
    }]
  });
};

// 加载数据
const loadData = (college) => {
  const data = mockData.value[college];
  if (pieChart) {
    pieChart.setOption({
      series: [{
        data: data,
        label: { show: computedLabelShow.value }
      }]
    });
  }
};

// 学院切换
watch(currentCollege, (newVal) => {
  loadData(newVal);
});

// 响应式变量 - 饼图标签显示
const showPieLabel = ref(false);
const computedLabelShow = computed(() => showPieLabel.value);

// 切换饼图标签
const togglePieLabel = () => {
  showPieLabel.value = !showPieLabel.value;
  pieChart?.setOption({
    series: [{ label: { show: showPieLabel.value } }]
  });
}
const handlePageChange = (page) => {
  currentPage.value = page;
  request.get('log/get-login-log', {
    params: {
      page: currentPage.value,
      size: 5
    }
  }).then(res => {
    dataLength.value = res.data.data['total']
    logData.value = res.data.data['logs']
  })
}
</script>

<style scoped lang="scss">
.college-statistics {
  padding: 24px;
  background-color: #f0f2f5;
  width: 85vw;
  .filter-card {
    margin-bottom: 24px;
    padding: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    border-radius: 12px;
  }

  .chart-row {
    .chart-card {
      height: 65vh;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
      border-radius: 16px;
      transition: transform 0.3s ease;

      &:hover {
        transform: translateY(-5px);
      }

      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 24px 16px;
        font-size: 1.125rem;
        font-weight: 500;

        .el-icon {
          font-size: 1.25rem;
          color: #6c757d;
          cursor: pointer;
          transition: color 0.3s;

          &:hover {
            color: #4a90e2;
          }
        }
      }

      .chart-container {
        height: 50vh;
        margin: 0 24px 24px;
      }
    }
  }
}
</style>
